<template>
  <el-row class="login-container" justify="center" :align="'middle'">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt=""></img>
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="handChange">{{fromType?'已有账号，去登录':'没有账号，去注册'}}</el-link>
      </div>
      <el-form :model="loginForm" label-width="120px" v-if="fromType===0" :rules="rules" ref="ruleFromRef">
        <el-form-item label="账号" prop="account">
          <el-input v-model="loginForm.account" placeholder="请输入账号" :prefix-icon="Postcard" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" placeholder="请输入密码" :prefix-icon="Lock" type="password" clearable></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="registerForm" label-width="120px" v-else :rules="rules" ref="ruleFromRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" :prefix-icon="UserFilled" clearable></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="registerForm.account" placeholder="请输入账号" :prefix-icon="Postcard" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" placeholder="请输入密码" :prefix-icon="Lock" type="password" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色" v-if="fromType===1">
          <el-radio-group v-model="registerForm.role" size="18">
            <el-radio-button label="学生" value="1" />
            <el-radio-button label="老师" value="2" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="row-button">
        <el-button type="primary" @click="loginCount(ruleFromRef)"  style="width: 40%" v-if="fromType===0">登录</el-button>
        <el-button type="primary" @click="registerCount(ruleFromRef)" style="width: 40%" v-else>注册</el-button>
      </div>
    </el-card>
  </el-row>
</template>
<script setup>
import {reactive, ref,computed,toRaw} from 'vue'
import {Postcard, UserFilled,Lock} from "@element-plus/icons-vue"
import {Login,Register} from '../../api/index.js'
import {ElMessage} from "element-plus";
import {useRouter} from 'vue-router'
import {useStore} from 'vuex'
//表单的状态（0表示登录页面，1表示注册页面）
const fromType= ref(0)


const routerList=computed(()=> store.state.menu.routerList)
const store=useStore()
const router=useRouter()
const ruleFromRef= ref()
//表单数据对象
const loginForm = reactive({
  account: '',
  password: ''
})
const registerForm = reactive({
  username: '',
  password: '',
  account: '',
  role: '1'
})
const validateAccount=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('账号不能为空'))
  }else{
    const uPattern = /^[a-zA-Z0-9_-]{4,16}$/
    uPattern.test(value)?callback():callback(new Error('账号格式不正确'))
  }
}
const validatePassword=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('密码不能为空'))
  }else{
    const uPass = /^[a-zA-Z0-9_-]{4,16}$/
    uPass.test(value)?callback():callback(new Error('密码格式不正确'))
  }
}
const validateUsername=(rule,value,callback)=>{
  if(value===''){
    callback(new Error('用户名不能为空'))
  }else{
    callback()
  }
}
const rules=reactive({
  account:[{validator:validateAccount,trigger:'blur'}],
  password:[{validator:validatePassword,trigger:'blur'}],
  username:[{validator:validateUsername,trigger:'blur'}]
})
const imgUrl=new URL('../../../public/login-head.png', import.meta.url).href
const handChange=()=>{
  fromType.value =fromType.value?0:1
}
const loginCount=async (formEl)=>{
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
  Login(loginForm).then(({data})=>{
    if (data.code===200){
      ElMessage({
        message:'登录成功',
        type:'success'
      })
      localStorage.setItem('token',data.token)
      localStorage.setItem('userInfo',JSON.stringify(data.data))
      store.commit('dynamicMenu',data.route.children)
      toRaw(routerList.value).forEach(item=>{
        router.addRoute('main',item)
      })
      console.log(routerList,'routerlist')
      router.push('/dashboard')
    }else if (data.code===201){
      // ElMessage({
      //   message: '账号或密码错误',
      //   type: 'warning'
      // })
      ElMessage.warning(data.message)
    }
  })
}
const registerCount=async (formEl)=>{
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
  Register(registerForm).then(({data})=>{
    if (data.code===200){
      ElMessage({
        message:'注册成功',
        type:'success'
      })
    }else if (data.code===201){
      ElMessage({
        message: '账号重复',
        type: 'warning'
      })
    }
  })
}
</script>
<style scoped lang="less">
:deep(.el-card__header) {
  padding: 0
}
.login-container {
  height: 100%;
  .card-header{
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
  .row-button {
    text-align: center;
  }
}
</style>
